﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


using Kooboo.Web.Mvc.Paging;

using Kooboo.Web.Mvc;


namespace Kooboo.Web.Controllers
{
    using Kooboo.Commerce;
    using Kooboo.Commerce.Contexts.Products;
    using Kooboo.Commerce.Services;
    using Kooboo.IoC;

    public class ProductController : ControllerBase
    {
        //
        // GET: /Product/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult View(int id, int? page)
        {
            this.BindViewData();

            var categories = new CategoryService();

            var category = categories.GetCategoriesByProductId(id)
                .OrderBy(i => i.Children.Count())
                .FirstOrDefault();

            this.Select(category);


            var serviceClient = new ProductService();

            var product = serviceClient.GetProductById(id);

            var prices = product.Sales.Min(i => i.Price).ToString("C") + " - " + product.Sales.Max(i => i.Price).ToString("C");

            var stocks = product.Sales.Min(i => i.Stock) + " - " + product.Sales.Max(i => i.Stock);

            var deliveryDays = product.Sales.Min(s => s.DeliveryDays) + " - " + product.Sales.Max(s => s.DeliveryDays);

            this.ViewData["AddCartAction"] = this.Url.Action<CartController>(m => m.Add(UrlParameter<int>.Empty, UrlParameter<int>.Empty));

            this.ViewData["QuestionAction"] = this.Url.Action("Question", new { productId = product.Id });

            this.ViewData["ReviewAction"] = this.Url.Action("Review", new { productId = product.Id });

            this.ViewData["Username"] = this.Request.IsAuthenticated ? ViewBag.LoggedName : String.Empty;

            this.ViewData["UserEmail"] = this.Request.IsAuthenticated ? ContextContainer.Current.Resolve<Kooboo.Connect.User>().Email : String.Empty;

            //Review form
            if (RouteData.Values.Keys.Contains("orderid"))
            {
                String _reviewOrderId = RouteData.Values["orderid"].ToString();
                int reviewOrderId;
                if (Int32.TryParse(_reviewOrderId, out reviewOrderId) && reviewOrderId > 0)
                {
                    var user = ContextContainer.Current.Resolve<Kooboo.Connect.User>();
                    if (user != null)
                    {
                        var customer = user.GetCustomer();
                        if (customer != null && customer.Id > 0)
                        {
                            var orderService = new OrderService();
                            var validOrder = orderService.GetOrderForReview(reviewOrderId, customer.Id, product.Id, OrderStatus.DeliveryCompleted);
                            if (validOrder != null)
                            {
                                int count = product.Reviews.Where(r => r.Customer.Id == customer.Id && r.Order.Id == reviewOrderId).Count();
                                if (count == 0) //didn't post review for this order
                                {
                                    this.ViewData["Order"] = validOrder;
                                }
                            }
                        }
                    }
                }
            }

            return View(new
            {
                Prices = prices,
                Stocks = stocks,
                DeliveryDays = deliveryDays,
                product.Id,
                product.BrandName,
                BrandUrl = this.Url.Action<BrandController>(m => m.Index(product.BrandId, null, null)),
                product.Description,
                Images = GetProductImages(product),
                product.Name,
                product.Questions,
                QuestionCount = product.Questions.Length,
                product.Reviews,
                ReviewCount = product.Reviews.Where(r => r.IsPublished).Count(),
                product.Specification,
                product.Sales,
                product.SkuAlias
            });
        }

        private String[] GetProductImages(Product product)
        {
            if (product == null || product.Images == null || product.Images.Length <= 0)
            {
                //use default Image
                return new String[] { Configuration.ImageNotAvailable_Detail };
            }
            else
            {
                return product.Images;
            }
        }

        [HttpPost]
        public ActionResult Question(IProductQuestion model)
        {
            model.QuestionDate = DateTime.Now;
            var host = new ServiceHost();
            host.Post(model);

            return Json(true);
        }

        public ActionResult Question(Int32 productId, int? page)
        {
            var serviceClient = new ProductService();
            return Json(serviceClient.GetProductQuestions(productId, page, 10), JsonRequestBehavior.AllowGet);
        }


        [HttpPost]
        public ActionResult Review(IProductReview review)
        {
            var customer = ContextContainer.Current.Resolve<Kooboo.Connect.User>().GetCustomer();
            review.CreateDate = DateTime.Now;
            review.Customer = customer;
            var host = new ServiceHost();
            host.Post(review);
            return Json(true);
        }

        public ActionResult Review(Int32 productId, int? page)
        {
            var serviceClient = new ProductService();
            return Json(serviceClient.GetProductReviews(productId, page, 10), JsonRequestBehavior.AllowGet);
        }

        protected override void Execute(System.Web.Routing.RequestContext requestContext)
        {
            base.Execute(requestContext);
        }
    }
}
